"""
附加分审查模块序列化器
"""
from rest_framework import serializers
from django.contrib.auth.models import User
from .models import ExtraReview


class ExtraReviewStudentSerializer(serializers.ModelSerializer):
    """学生信息序列化器（用于附加分审查）"""
    student_id = serializers.CharField(source='profile.student_id', read_only=True)
    class_name = serializers.CharField(source='profile.class_name', read_only=True)
    
    class Meta:
        model = User
        fields = ['id', 'username', 'student_id', 'class_name']


class ExtraReviewSerializer(serializers.ModelSerializer):
    """附加分审查序列化器"""
    student = ExtraReviewStudentSerializer(read_only=True)
    student_id = serializers.IntegerField(write_only=True, required=False)
    status = serializers.SerializerMethodField()
    
    class Meta:
        model = ExtraReview
        fields = [
            'id', 'sort', 'name', 'ranks', 'levels', 'picture',
            'grade', 'first_efficient', 'second_efficient', 'third_efficient',
            'time', 'student', 'student_id', 'classes', 'auditor', 'status',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def get_status(self, obj):
        """获取审核状态"""
        if obj.first_efficient and obj.second_efficient and obj.third_efficient:
            return 'approved'
        elif not obj.third_efficient:
            return 'pending_monitor'  # 待班委审核
        elif not obj.second_efficient:
            return 'pending_counselor'  # 待辅导员审核
        elif not obj.first_efficient:
            return 'pending_office'  # 待学工办审核
        return 'pending'
    
    def create(self, validated_data):
        """创建附加分申请，自动关联当前用户并匹配分数"""
        from certificate.models import Certificate
        
        request = self.context.get('request')
        if request and hasattr(request, 'user'):
            validated_data['student'] = request.user
            # 自动填充班级信息
            if hasattr(request.user, 'profile'):
                validated_data['classes'] = request.user.profile.class_name or ''
        
        # 根据证书信息匹配分数
        try:
            certificate = Certificate.objects.filter(
                sort=validated_data.get('sort'),
                name=validated_data.get('name'),
                ranks=validated_data.get('ranks'),
                classes=validated_data.get('levels')  # levels对应Certificate的classes
            ).first()
            
            if certificate:
                validated_data['grade'] = certificate.grade
        except Exception:
            pass  # 如果匹配失败，分数为null
        
        return super().create(validated_data)


class ExtraReviewListSerializer(serializers.ModelSerializer):
    """附加分审查列表序列化器（简化版）"""
    student_name = serializers.CharField(source='student.username', read_only=True)
    student_id = serializers.CharField(source='student.profile.student_id', read_only=True)
    status = serializers.SerializerMethodField()
    
    class Meta:
        model = ExtraReview
        fields = [
            'id', 'name', 'ranks', 'levels', 'picture', 'grade', 
            'student_name', 'student_id', 'classes', 'time', 'status',
            'created_at'
        ]
    
    def get_status(self, obj):
        """获取审核状态"""
        if obj.first_efficient and obj.second_efficient and obj.third_efficient:
            return 'approved'
        return 'pending'
